console.log('preload.js 已加载！');

const { contextBridge, ipcRenderer, shell } = require('electron');
const { electronAPI } = require('@electron-toolkit/preload');

console.log('electronAPI 是否存在:', !!electronAPI);

if (electronAPI) {
    contextBridge.exposeInMainWorld('electron', electronAPI);
} else {
    console.error('@electron-toolkit/preload 的 electronAPI 未找到');
}

// 暴露更新相关API
const updaterAPI = {
    onUpdateMessage: (callback) => {
        ipcRenderer.on('update-message', (_event, ...args) => callback(...args));
    },
    quitAndInstall: () => {
        ipcRenderer.send('quit-and-install-update');
    },
    checkForUpdate: () => {
        ipcRenderer.send('check-for-update-trigger');
    },
    startDownloadUpdate: () => {
        ipcRenderer.send('start-download-update');
    },
    cleanUpdateCache: () => {
        ipcRenderer.send('clean-update-cache');
    }
};

// 暴露窗口控制API
const windowControlAPI = {
    minimizeWindow: () => ipcRenderer.send('minimize-window'),
    toggleMaximizeWindow: () => ipcRenderer.send('maximize-window'),
    closeWindow: () => ipcRenderer.send('close-window'),
    startDrag: () => ipcRenderer.send('start-drag'),
    getIsMaximized: () => ipcRenderer.sendSync('is-maximized'),
    onWindowMaximized: (callback) => ipcRenderer.on('window-maximized', callback),
    onWindowUnmaximized: (callback) => ipcRenderer.on('window-unmaximized', callback)
};

// 暴露shell相关API
const shellAPI = {
    openExternal: (url) => {
        return shell.openExternal(url);
    }
};

// 关键补充：暴露认证相关API，用于传递token到主进程
const authAPI = {
    setAuthToken: (token) => {
        console.log('preload: 转发token到主进程', token ? 'token存在' : 'token为空');
        ipcRenderer.send('set-auth-token', token);
    }
};

// 向渲染进程暴露API
contextBridge.exposeInMainWorld('updater', updaterAPI);
contextBridge.exposeInMainWorld('windowControl', windowControlAPI);
contextBridge.exposeInMainWorld('shellAPI', shellAPI);
contextBridge.exposeInMainWorld('authAPI', authAPI);